<?php
class BbsController extends Controller
{
	public function filters()
	{
		return array(
            'accessControl',
		);
	}
	public function accessRules()
	{
		return array(
		array('allow',
	                'actions'=>array('index','list','view','category'),
	                'users'=>array('*'),
		),
		array('allow',
			        'actions'=>array('new','reply','user'),
			        'users'=>array('@'),
		),
		array('allow',
	                'actions'=>array('add', 'delete','admin','postadmin','postsave'),
	                'users'=>array('ilookadmin',"gaopengfei"),
		),
		array('deny',
	                'users'=>array('*'),
		),
		);
	}
	public function actionIndex()
	{
		$this->redirect("category",array("id"=>'1'));
	}
	public function actionCategory()
	{
		$this->pageTitle = "掌上论坛";
		$this->pageDescription="新加坡华人论坛，新加坡论坛。狮城华人论坛";
		$this->pageKeywords="iLook-新加坡,狮城水库,狮城杂谈,新加坡留学,新加坡求职,新加坡交友,新加坡华人论坛,新加坡论坛,狮城华人论坛";
		$bbsies = BbsCategory::model()->findAll("parent_id=1 order by hits desc");
		$this->render("category",array("bbsies"=>$bbsies));
	}
	//帖子列表
	public function actionList($id=1){
		$bbs = $this->loadByPk($id);
		//bbs点击+1
		$bbs->hits++;
		$bbs->save();

		$this->pageTitle="狮城掌上论坛-{$bbs->title}";
		$this->pageDescription=$this->pageTitle;
		$this->pageKeywords = $this->pageTitle;

		$criteria = new CDbCriteria;
		

		if($id !=1){
			$criteria -> order ='updated desc';
			$criteria -> condition = "category_id=$id and (flag='active' or flag = 'featured' )";
		}else{
			$criteria -> order ='created desc';
			$criteria -> condition = "flag='active' or flag = 'featured'";
		}
		$pages = new CPagination(BbsTopic::model() -> count($criteria));
		$pages -> pageSize =20;
		$pages -> applyLimit($criteria);		
		$topics = BbsTopic::model()->findAll($criteria);
		
		$this->render('list',array(
			'bbs'=>$bbs,
			'topics'=>$topics,
			'pages'=>$pages,
		));
	}
	//查看帖子内容
	public function actionView($id,$see_lz=null){
		$topic = $this->loadTopicByPk($id);
		//帖子点击+1
		$topic->hits++;
		$topic->save();
		
		if(isset($_POST['BbsPost'])){
			$post= new BbsPost();
			$post->attributes = $_POST['BbsPost'];
			
			//未登陆者禁止插入图片
			$upload=null;
			if(!Yii::app()->user->isGuest){
				if(!empty($_FILES)){						
					foreach ($_FILES['image']['name'] as $i => $name) {
						if ($_FILES['image']['error'][$i] == 4) {
							continue;
						}
						if ($_FILES['image']['error'][$i] == 0) {
							if(!$this->isAllowedExtension($name)) {
								continue;
							}
							if ($_FILES['image']['size'][$i] > 1000000) {
								continue;
							}
								
							$photo = new BbsPhoto();
							$photo->member_id = Yii::app()->user->id;
							$photo->save();
								
							$file = Yii::app()->basePath."/../images/bbs/upload/{$photo->id}.png";
							$image_file=CUploadedFile::getInstanceByName("image[$i]");
							$image_file->saveAs("$file");
							$image = new Image();
							$image->generate_image_resize($file, $file, 300, 600);
							$upload = $upload."<br/><img src='".Yii::app()->baseUrl."/images/bbs/upload/{$photo->id}.png' />";
						}
					}
				}
				$post->content = $post->content.$upload;
				//插入图片完成
			}
				
			if(!Yii::app()->user->isGuest){
				$post->member_id = Yii::app()->user->id;
				if(UserIdentity::getUserDetail(Yii::app()->user->id)->nickname==null){
					$member = Member::model()->findByPk(Yii::app()->user->id);
					$post->author = $member->username;
				}else{
					$post->author = UserIdentity::getUserDetail(Yii::app()->user->id)->nickname;
				}
			}else{
				$post->author = $_SERVER['REMOTE_ADDR'];
			}	

			$post->flag='active';
			$post->save();
			//回复+1
			$topic->post='1';
			$topic->comments++;
			$topic->save();
		}
		
		$bbs = $this->loadByPk($topic->category_id);
			
		$this->pageTitle="{$bbs->title}-{$topic->title}";
		$this->pageDescription=$this->pageTitle;
		$this->pageKeywords = $this->pageTitle;
		
		$criteria = new CDbCriteria;
		$criteria -> order ='created';
		if($see_lz==1){
			$criteria -> condition = "topic_id=$id and member_id=$topic->member_id";
		}else{
			$criteria -> condition = "topic_id=$id";
		}
		$pages = new CPagination(BbsPost::model() -> count($criteria));
		$pages -> pageSize =20;
		$pages -> applyLimit($criteria);
		$posts = BbsPost::model()->findAll($criteria);
		
		$this->render('view',array(
					'bbs'=>$bbs,
					'topic'=>$topic,
					'pages'=>$pages,
					'posts'=>$posts,
					'see_lz'=>$see_lz,
		));	
	}
	//帖子
	public function actionNew($id){
		$bbs = $this->loadByPk($id);
		//发帖
		if(isset($_POST['BbsPost'])){
			$post= new BbsPost();
			$post->attributes = $_POST['BbsPost'];
			
			//插入图片
			$upload=null;
			if(!empty($_FILES)){
				foreach ($_FILES['image']['name'] as $i => $name) {
					if ($_FILES['image']['error'][$i] == 4) {
						continue;
					}
					if ($_FILES['image']['error'][$i] == 0) {
						if(!$this->isAllowedExtension($name)) {
							continue;
						}
						if ($_FILES['image']['size'][$i] > 1000000) {
							continue;
						}
						
						$photo = new BbsPhoto();
						$photo->member_id = Yii::app()->user->id;
						$photo->save();

						$file = Yii::app()->basePath."/../images/bbs/upload/{$photo->id}.png";
						$image_file=CUploadedFile::getInstanceByName("image[$i]");
						$image_file->saveAs("$file");
						$image = new Image();
						$image->generate_image_resize($file, $file, 300, 600);
						$upload = $upload."<img src='".Yii::app()->baseUrl."/images/bbs/upload/{$photo->id}.png' /><br/>";
					}
				}
			}
			$post->content = $upload.$post->content;
			//插入图片完成
			

			if(!empty($post->title) && strlen($post->content)>10){
				$post->member_id = Yii::app()->user->id;
				$member = Member::model()->findByPk(Yii::app()->user->id);
				if(UserIdentity::getUserDetail(Yii::app()->user->id)->nickname==null){
					$post->author = $member->username;
				}else{
					$post->author = UserIdentity::getUserDetail(Yii::app()->user->id)->nickname;
				}		
				$topic = new BbsTopic();
				$topic->title = $post->title;
				$topic->category_id = $bbs->id;
				$topic->category = $bbs->title;
				$topic->member_id = Yii::app()->user->id;
				if(UserIdentity::getUserDetail(Yii::app()->user->id)->nickname==null){
					$topic->author = $member->username;
				}else{
					$topic->author = UserIdentity::getUserDetail(Yii::app()->user->id)->nickname;
				}
				$topic->flag = 'active';
				$topic->post='1';
				$topic->save();
				$post->flag='active';
				$post->topic_id = $topic->id;
				$post->save();
					
				$this->redirect(array("bbs/view","id"=>"$topic->id"));
			}
			else {
				$this->render('new',array(
									'bbs'=>$bbs,
									'post'=>$post,
									'error'=>'您提交的内容不符合论坛要求，标题为必填，内容不能少于10个字！',
				));
			}
		}
		else if($bbs->id!=1){
			$post = new BbsPost();
			$this->render('new',array(
					'bbs'=>$bbs,
					'post'=>$post,
			));	
		}
		else{
			$this->redirect(array("site/page","view"=>"error"));
		}
	}
	//完整回复
	public function actionReply($id,$title=null){
		$topic = $this->loadTopicByPk($id);
	
		if(isset($_POST['BbsPost'])){
			$post= new BbsPost();
			$post->attributes = $_POST['BbsPost'];
			if(strlen($post->content)>5){	
				//插入图片
				$upload=null;
				if(!empty($_FILES)){
					foreach ($_FILES['image']['name'] as $i => $name) {
						if ($_FILES['image']['error'][$i] == 4) {
							continue;
						}
						if ($_FILES['image']['error'][$i] == 0) {
							if(!$this->isAllowedExtension($name)) {
								continue;
							}
							if ($_FILES['image']['size'][$i] > 1000000) {
								continue;
							}
				
							$photo = new BbsPhoto();
							$photo->member_id = Yii::app()->user->id;
							$photo->save();
				
							$file = Yii::app()->basePath."/../images/bbs/upload/{$photo->id}.png";
							$image_file=CUploadedFile::getInstanceByName("image[$i]");
							$image_file->saveAs("$file");
							$image = new Image();
							$image->generate_image_resize($file, $file, 300, 600);
							$upload = $upload."<img src='".Yii::app()->baseUrl."/images/bbs/upload/{$photo->id}.png' /><br/>";
						}
					}
				}
				$post->content = $upload.$post->content;
				//插入图片完成
				
				$post->member_id = Yii::app()->user->id;
				$member = Member::model()->findByPk(Yii::app()->user->id);
				if(UserIdentity::getUserDetail(Yii::app()->user->id)->nickname==null){
					$post->author = $member->username;
				}else{
					$post->author = UserIdentity::getUserDetail(Yii::app()->user->id)->nickname;
				}
				$post->topic_id = $topic->id;
				$post->flag='active';
				$post->save();
				$topic->post='1';
				$topic->comments++;
				$topic->save();
				$this->redirect(array("bbs/view","id"=>"$topic->id"));
			}
			else {
				$this->render('reply',array(
						'topic'=>$topic,
						'title'=>$title,
						'post'=>$post,
						'error'=>'您提交的内容不符合论坛要求，内容不能少于5个字！',
				));
			}
		}
		else{
			$post = new BbsPost();
			$post->title =$title;
			$this->render('reply',array(
						'topic'=>$topic,
						'post'=>$post,
			));
		}
	}
	//Category编辑
	public function actionAdmin($id=1){
		if(isset($_POST["BbsCategory"])){
			foreach($_POST["BbsCategory"] as $bbsArr){
				$bbs = BbsCategory::model()->findByPk($bbsArr['id']);
				$bbs->attributes=$bbsArr;
				$image_file=CUploadedFile::getInstanceByName("BbsCategory[$bbs->id][image_file]");
				if($bbs->save()){
					if(!empty($image_file)){
						$file = Yii::app()->basePath."/../images/bbs/{$bbs->id}.png";
						$image_file->saveAs("$file");
					}
				}
			}
		}
		$bbsies = BbsCategory::model()->findAll("parent_id=$id");
		$curr_bbs = $id!=0? BbsCategory::model()->findByPk($id):null;
		$this->render('admin',array("bbsies"=>$bbsies,"curr_bbs"=>$curr_bbs));
	}
	//添加Category
	public function actionAdd($id){
		$bbs = new BbsCategory;
		$bbs->parent_id=$id;
		$bbs->title="未命名";
		$bbs->save();
		$this->redirect(array("bbs/admin","id"=>$id));
	}
	//删除Category
	public function actionDelete($id){
		$bbs = BbsCategory::model()->findByPk($id);
		$parent_id = $bbs->parent_id;
		if(BbsCategory::model()->count("parent_id=$id")!=0 ||BbsTopic::model()->count("category_id=$id")!=0){
			Yii::app()->user->setFlash('failure','操作失败，你必须先删除该列表下地所有子类和名片！');
		}else{
			$file = Yii::app()->basePath."/../images/bbs/{$bbs->id}.png";
			if(is_file($file)){
				unlink($file);
			}
			$bbs->delete();
		}
		$this->redirect(array("bbs/admin","id"=>$parent_id));
	}
	

	//Post后台
	public function actionPostadmin($id=null){
 		if(empty($id)){
 			$this->render('postadmin');
 		}
		else{
		$topic= BbsTopic::model()->findByPK($id);
			if (isset($topic)){
				if(isset($_GET['delete'])){
					//删除此贴
					BbsPost::model()->deleteAll("topic_id=$topic->id");
					$topic->delete();
					$info = "帖子删除成功！";
					$this->render('postadmin',array(
											'id'=>$topic->id,
											'info'=>$info,
					));
				}
				$info=null;
				if(isset($_GET['edit'])){
					//edit posts
					$bbs =  $this->loadByPk($_GET['BbsTopic']['category_id']);
					$topic->category_id = $bbs->id;
					$topic->category=$bbs->title;
					$topic->title=$_GET['BbsTopic']['title'];
					if ($_GET['BbsTopic']['featured']==1){
						$topic->flag='featured';
					}else{
						$topic->flag='active';
					}
					if ($_GET['BbsTopic']['top']==1){
						//置顶功能
						$topic->updated='2030-10-19 13:09:50';
					}else{
						$topic->updated =$this->getLatestPost($topic->id)->created;
					}
					$topic->save();
					$info ='主题编辑成功';
				}
				
				$criteria = new CDbCriteria;
				$criteria -> order ='created';
				$criteria -> condition = "topic_id=$topic->id";
				$pages = new CPagination(BbsPost::model() -> count($criteria));
				$pages -> pageSize =20;
				$pages -> applyLimit($criteria);
				$posts = BbsPost::model()->findAll($criteria);
				
				$this->render('postadmin',array(
						'id'=>$topic->id,
						'topic'=>$topic,
						'posts'=>$posts,
						'info'=>$info,
						'pages'=>$pages,
				));
				
				
			}else{
				$error = "您搜索的帖子不存在！";
				$this->render('postadmin',array(
						'error'=>$error,
				));
			}
		}
	}
	
	public function actionPostsave(){
		$topic= $this->loadTopicByPk($_POST['id']);
		if(isset($_POST['save'])){
			//edit posts
			$posts = $_POST['BbsPost'];
			foreach($posts as $post){
				$post2 = BbsPost::model()->findByPK($post['id']);
				$post2->title =$post['title'];
				$post2->content=$post['content'];
				$post2->flag=$post['hide']==1?"inactive":"active";
				$post2->save();
			}
			$info ='帖子编辑成功';
		}

		$criteria = new CDbCriteria;
		$criteria -> order ='id';
		
		$criteria -> condition = "topic_id=$topic->id";
		$pages = new CPagination(BbsPost::model() -> count($criteria));
		$pages -> pageSize =20;
		$pages -> applyLimit($criteria);
		$posts = BbsPost::model()->findAll($criteria);

		$this->render('postadmin',array(
							'id'=>$topic->id,
							'topic'=>$topic,
							'posts'=>$posts,
							'info'=>$info,
							'pages'=>$pages,
		));
	}
	public function actionUser($id=null){
		if (empty($id)){
			$topics = BbsTopic::model()->findAll("member_id=".Yii::app()->user->id." order by id desc limit 20");
			$posts = BbsPost::model()->findAll("member_id=".Yii::app()->user->id." order by id desc limit 20");
			$this->render("user",array(
						"topics"=>$topics,
						"posts"=>$posts,
					));
		}
		else{
			$member = $this->getUserByPK($id);
			$topics = BbsTopic::model()->findAll("member_id=".$id." order by id desc limit 20");
			$posts = BbsPost::model()->findAll("member_id=".$id." order by id desc limit 20");
			$this->render("user",array(
					"topics"=>$topics,
					"posts"=>$posts,
					"id"=>$id,
					"username"=>$member->username,));
		}
	}

	private function loadByPk($pk){
		$model = BbsCategory::model()->findByPk($pk);
		if(isset($model)){
			return $model;
		}else{
			$this->redirect(array("site/page","view"=>"error"));
		}
	}
	private function getUserByPK($pk){
		$model = Member::model()->findByPk($pk);
		if(isset($model)){
			return $model;
		}else{
			$this->redirect(array("site/page","view"=>"error"));
		}
	}
	private function loadTopicByPk($pk){
		$model = BbsTopic::model()->findByPk($pk);
		if(isset($model)){
			return $model;
		}else{
			$this->redirect(array("site/page","view"=>"error"));
		}
	}
	private function getLatestPost($pk){
		$criteria = new CDbCriteria;
		$criteria -> order ='id desc';
		$criteria -> condition = "topic_id=$pk";
		$criteria -> limit = "1";
		$posts= BbsPost::model()->findAll($criteria);
		$model = new BbsPost();
		foreach($posts as $post){
			$model = $post;
		}
		return $model;
	}
	private function isAllowedExtension($fileName) {
		$allowedExtensions = array("jpg", "png", "gif");
		return in_array(end(explode(".", $fileName)), $allowedExtensions);
	}
}